package cn.codingjc.peekaboo.application.service.base;

import cn.codingjc.peekaboo.domain.repository.UserRepository;
import cn.codingjc.peekaboo.infrastructure.persistence.po.SysRolePO;
import cn.codingjc.peekaboo.infrastructure.persistence.po.SysUserPO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @auther: codingjc
 * @date:   2023/4/19
 */

@Slf4j
@Service
@AllArgsConstructor
public class UserService implements UserDetailsService {

   private final UserRepository userRepository;

   @Override
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      SysUserPO sysUserPO = userRepository.getUserByUsername(username);
      if (null == sysUserPO) {
         throw new UsernameNotFoundException("用户不存在！");
      }
      // 设置角色
      try {
         List<SysRolePO> sysRolePOList = userRepository.getSysRolesByUserId(sysUserPO.getUserId());
         sysUserPO.setRoles(sysRolePOList);
         // 设置权限
         Set<String> permissions = userRepository.getPermissionsByUserId(sysUserPO.getUserId());
         sysUserPO.setPermissions(permissions);
      } catch (Exception e) {
         log.error("get info error:", e);
      }
      return sysUserPO;
   }

}
